﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using Castle.DynamicProxy;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using JavaNET;
using ProtoBuf;
using System.Text;
using System.Security.Principal;
using JavaNET.communication;
using JavaNET.context;

namespace JavaNET.mvc
{
    public class JavaNETControllerFactory : DefaultControllerFactory
    {
        static Dictionary<Type, Object> cachedProxies = new Dictionary<Type, Object>();

        public override IController CreateController(RequestContext context, string controllerName)
        {
            IController controller = base.CreateController(context, controllerName);
            // check, if there is a JavaNETFacadeAttribute field
            var fields = controller.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                .Where(x => x.GetCustomAttributes(typeof(JavaNETFacadeAttribute), false).Length > 0);
            if (fields.Count() > 0)
            {
                String appUserName = context.HttpContext.User.Identity.Name;
                String netMachineName = context.HttpContext.Server.MachineName;
                JavaNETDefaultFacadeContext facadeContext = new JavaNETDefaultFacadeContext();
                facadeContext.netMachineName = netMachineName;
                facadeContext.appUserName = appUserName;

                foreach (FieldInfo field in fields)
                {
                    // create proxy for the field
                    Object proxy = null;
                    if (cachedProxies.ContainsKey(field.FieldType))
                    {
                        Debug.WriteLine("found proxy in cache...");
                        bool b = cachedProxies.TryGetValue(field.FieldType, out proxy);
                    }
                    else
                    {
                        Debug.WriteLine("creating proxy...");
                        proxy = JavaNETCommunicationProxyFactory.WrapAs(field.FieldType, facadeContext);
                        cachedProxies.Add(field.FieldType, proxy);
                    }
                    field.SetValue(controller, proxy);
                }
            }



            return controller;

        }
    }

}